
package com.kim.pong.service

import com.google.common.util.concurrent.RateLimiter
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.web.reactive.function.server.ServerRequest
import spock.lang.Specification

class PongServiceSpec extends Specification {

    def logger = LoggerFactory.getLogger(PongServiceSpec.class)
    def rateLimiter = Mock(RateLimiter)
    def pongService = new PongService(rateLimiter)

    def "handlePing should return 'World' when rate limiter allows"() {
        given:
        def request = Mock(ServerRequest)
        rateLimiter.tryAcquire() >> true

        when:
        def response = pongService.handlePing(request)

        then:
        1 * rateLimiter.tryAcquire() >> true
        response.block().statusCode() == HttpStatus.OK
    }

    def "handlePing should return 'Too many requests' when rate limiter denies"() {
        given:
        def request = Mock(ServerRequest)
        rateLimiter.tryAcquire() >> false

        when:
        def response = pongService.handlePing(request)

        then:
        1 * rateLimiter.tryAcquire() >> false
        response.block().statusCode() == HttpStatus.TOO_MANY_REQUESTS
    }

    def "getTrackingNumber should return a unique tracking number"() {
        when:
        def trackingNumber = pongService.getTrackingNumber()

        then:
        trackingNumber.endsWith(" - ")
    }
}